package com.zzyl.intercept;


import com.zzyl.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        log.info("携带的token为：{}", token);
        if (!StringUtils.hasLength(token)) {//这里用这个StringUtils.hasLength是为了剔除字符串为空和字符串中有0个以上空格的情况
            response.setStatus(401);
            return false;
        }
        //4.解析token，如果解析失败直接相应401否者放行
        try {
            Claims claims = JwtUtil.parseJWT("itheima", token);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析令牌失败，返回错误信息");
            response.setStatus(401);
            return false;
        }
        return true;
    }
}



